package com.itheima.list_set;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class HashSetTest {

    // HashSet 集合
    public static void main(String[] args) {
        demo1();

    }


    /**
     * 给HashSet中存放自定义类型元素时，
     * 需要重写对象中的hashCode和equals方法，
     * 建立自己的比较方式，才能保证HashSet集合中的对象唯一
     */
    private static void demo1() {
        HashSet hashSet = new HashSet();

        hashSet.add(new Dog("1", 1));
        hashSet.add(new Dog("1", 1));
        hashSet.add(new Dog("2", 2));


        System.out.println(hashSet.toString());
    }
}

class Dog {
    private String username;
    private int year;

    public Dog() {
    }

    public Dog(String username, int year) {
        this.username = username;
        this.year = year;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dog dog = (Dog) o;
        return year == dog.year &&
                Objects.equals(username, dog.username);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, year);
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}
